//
//  MYOAuthViewController.swift
//  Sina
//
//  Created by 王亮龙1 on 16/5/22.
//  Copyright © 2016年 lianglong. All rights reserved.
//

import UIKit
import SVProgressHUD

class MYOAuthViewController: UIViewController {
    
    let webView = UIWebView()
    //进度条
    let progressView = WebProgressView()

    
    //在loadView阶段 将 根视图 替换为 webView
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
       // view.backgroundColor = UIColor.cyanColor()
        
        //添加进度条
        view .addSubview(progressView)
        
        setUpNavItem()
        loadOAuthPage()
        webView.delegate = self
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss() 
    }
    
    
    //加载web页面
    private func loadOAuthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize" + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
    }
    
    
    //设置navBarItem
    private func setUpNavItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(MYOAuthViewController.close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账户", target: self, action: #selector(MYOAuthViewController.testAccount))
        
    }
    
    //navBarItem的点击方法
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    @objc private func testAccount() {
        
        //使用webView要使用js语句
        let jsString = "document.getElementById('userId').value = '13103637956', document.getElementById('passwd').value = 'hang88688HANG' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    

}

//遵守代理,在不同的网络阶段显示或取消用户等待指示器
extension MYOAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        //开始加载
        progressView.startAnimation()
       // SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //结束加载
        progressView.endAnimation()
        //SVProgressHUD.dismiss()
    }
    
    //授权成功后跳转 授权成功界面 ,获取code, 利用code获取token
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString ?? ""
        
        let successFlag = "code="
        if urlString.containsString(successFlag) {
           // print("授权成功")
            
            let range = urlString.rangeOfString(successFlag)!
            let code = urlString.substringFromIndex(range.endIndex)
           // print(code,urlString)
            
            MYUserAccountViewModel.shareUserAccountViewModel.loadAccountToken(code, finished: { (isSuccess) in
                
                //如果成功回调值为失败
                if isSuccess == false {
                    
                    SVProgressHUD.showWithStatus(APPErrorTip)
                    return
                }
                
                
                //MARK:如果成功回调为成功,发送通知,跳转欢迎界面
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
                
            })
            
            //不加载视图
            return false
        }
        return true
    }
    
}
